package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private VideoApi videoApi;

    /**
     * 查询用户列表userInfo
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        //1、调用API分页查询数据列表   Ipage<UserInfo>
        IPage<UserInfo> iPage = userInfoApi.findAll(page,pagesize);
        List<UserInfo> list = iPage.getRecords();
        for (UserInfo userInfo : list) {
            String key = Constants.USER_FREEZE + userInfo.getId();
            if (redisTemplate.hasKey(key)) {
                userInfo.setUserStatus("2");
            }
        }
        //2、需要将Ipage转化为PageResult
        PageResult result = new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
        //3、构造返回值
        return result;
    }

    /**
     * 根据id查询
     */
    public UserInfo findUserById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        //查询redis的冻结状态
        String key = Constants.USER_FREEZE + userId;
        if (redisTemplate.hasKey(key)) {
            userInfo.setUserStatus("2");
        }

        return userInfo;
    }
    /**
     * 查询指定用户发布的所有视频列表
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page,pagesize,uid);
    }

    /**
     * 查询动态
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1.调用API查询数据：Movment对象
        PageResult result = movementApi.findByUserId(uid,state,page,pagesize);
        //2.解析PageResult,获取Movment对象
        List<Movement> items = (List<Movement> )result.getItems();
        //3.转换成vo对象a
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds,null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null){
                MovementsVo vo = MovementsVo.init(userInfo,movement);
                vos.add(vo);
            }
        }
        //4.构造返回值
        result.setItems(vos);
        return result;
    }

    /**
     * 根据id查询动态记录详细信息
     */
    public MovementsVo findAllMovement(String movementId) {
        Movement movement = movementApi.findById(movementId);
        if (movement != null) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
            MovementsVo vo = new MovementsVo();
            BeanUtils.copyProperties(movement,vo);
            return MovementsVo.init(userInfo,movement);
        }else {
            return null;
        }
    }
    /**
     * 根据发布id分页查询评论
     */
    public PageResult findUserByIdComment(Integer page, Integer pagesize, String messageId) {
        //1.调用api查询评论列表
        List<Comment> list =  commentApi.findComments(messageId, CommentType.COMMENT,page,pagesize);
        //2.判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        Integer sum = list.size();
        Long count = Long.valueOf(sum);
        //3.提取所有用户id，调用UserInfoApi查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4.构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null){
                CommentVo vo = CommentVo.init(userInfo,comment);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,count,vos);
    }

    /**
     * 用户冻结
     */
    public Map userFreeze(Map params) {
        //1.构造key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //2.构造失效时间
        Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString());
        int day = 0;
        if (freezingTime == 1){
            day = 3;
        }else if (freezingTime == 2){
            day = 7;
        }
        //将数据存入redis先将map集合转换为json
        String value = JSON.toJSONString(params);
        if (day > 0){
            redisTemplate.opsForValue().set(key,value,day, TimeUnit.DAYS);
        }else {
            redisTemplate.opsForValue().set(key,value);
        }
        Map reMap = new HashMap();
        reMap.put("message","冻结成功");
        return reMap;
    }

    /**
     * 用户解冻
     */
    public Map userUnfreeze(Map params) {
        //1.构造key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        redisTemplate.delete(key);
        Map reMap = new HashMap();
        reMap.put("message","解冻成功");
        return reMap;
    }
}
